"""
实用的Photoshop TIFF图层解决方案

由于Photoshop的图层格式是专有的，Python库无法完全解析。
这里提供一个实用的解决方案：

1. 检测并显示图层信息（供用户了解）
2. 保留原始TIFF数据的完整性
3. 将JSON图片作为新图层添加到合成图像中
4. 提供清晰的用户指导
"""

import os
import uuid
import json
import requests
import numpy as np
from PIL import Image, ImageDraw, ImageFont
from io import BytesIO
from pathlib import Path
from datetime import datetime
from config import Config

try:
    import tifffile
    TIFFFILE_AVAILABLE = True
except ImportError:
    TIFFFILE_AVAILABLE = False

class PracticalTiffProcessor:
    """
    实用的TIFF处理器
    重点：保持原始文件完整性，正确处理JSON图片
    """
    
    def __init__(self):
        self.export_folder = Config.EXPORT_FOLDER
        self.upload_folder = Config.UPLOAD_FOLDER
    
    def analyze_tiff_structure(self, tiff_path):
        """
        分析TIFF文件结构，检测可能的图层信息
        """
        analysis = {
            'has_photoshop_data': False,
            'estimated_layers': 1,
            'file_size': 0,
            'dimensions': (0, 0),
            'photoshop_data_size': 0,
            'recommendations': []
        }
        
        try:
            file_path = Path(tiff_path)
            analysis['file_size'] = file_path.stat().st_size
            
            # 检查是否为PSD文件
            if file_path.suffix.lower() == '.psd':
                # PSD文件处理
                try:
                    from psd_tools import PSDImage
                    psd = PSDImage.open(tiff_path)
                    analysis['dimensions'] = (psd.width, psd.height)
                    analysis['estimated_layers'] = len(list(psd))
                    analysis['has_photoshop_data'] = True
                    analysis['recommendations'].append(f"检测到PSD文件，包含{analysis['estimated_layers']}个图层")
                except ImportError:
                    analysis['recommendations'].append("PSD文件需要psd-tools库")
                except Exception as e:
                    analysis['recommendations'].append(f"PSD文件分析失败: {e}")
            elif TIFFFILE_AVAILABLE:
                # TIFF文件处理
                with tifffile.TiffFile(tiff_path) as tif:
                    page = tif.pages[0]
                    analysis['dimensions'] = (page.shape[1], page.shape[0])
                    
                    # 检查Photoshop数据
                    if 34377 in page.tags:
                        ps_data = page.tags[34377].value
                        analysis['has_photoshop_data'] = True
                        analysis['photoshop_data_size'] = len(ps_data)
                        
                        # 基于数据大小估算图层数
                        if len(ps_data) > 15000:
                            analysis['estimated_layers'] = min(10, max(2, len(ps_data) // 2000))
                        elif len(ps_data) > 5000:
                            analysis['estimated_layers'] = 2
                        
                        analysis['recommendations'].append(
                            f"检测到Photoshop图层数据({len(ps_data)}字节)，估算有{analysis['estimated_layers']}个图层"
                        )
                    else:
                        analysis['recommendations'].append("未检测到Photoshop图层数据，可能是标准TIFF格式")
            else:
                # 使用PIL获取基本信息
                try:
                    with Image.open(tiff_path) as img:
                        analysis['dimensions'] = img.size
                        analysis['recommendations'].append("建议安装tifffile库以获得更好的TIFF支持")
                except Exception as e:
                    analysis['recommendations'].append(f"无法读取文件: {e}")
        
        except Exception as e:
            analysis['recommendations'].append(f"分析文件时出错: {e}")
        
        return analysis
    
    def create_enhanced_tiff(self, template, regions, customization_data, custom_filename=''):
        """
        创建增强的TIFF文件
        策略：保留原始文件，合成JSON图片
        """
        print("=== 开始创建增强TIFF文件 ===")
        
        # 1. 分析原始文件
        original_analysis = None
        original_image = None
        canvas_width = template['width']
        canvas_height = template['height']
        
        if template.get('image_path'):
            image_path = template['image_path']
            if Path(image_path).is_absolute():
                template_image_path = Path(image_path)
            else:
                template_image_path = self.upload_folder / image_path
                
            if template_image_path.exists():
                print(f"分析原始TIFF: {template_image_path}")
                original_analysis = self.analyze_tiff_structure(str(template_image_path))
                
                print(f"文件分析结果:")
                print(f"  尺寸: {original_analysis['dimensions']}")
                print(f"  估算图层数: {original_analysis['estimated_layers']}")
                print(f"  Photoshop数据: {original_analysis['photoshop_data_size']} 字节")
                
                # 使用原始尺寸
                canvas_width, canvas_height = original_analysis['dimensions']
                
                # 加载原始图片
                original_image = Image.open(template_image_path)
                if original_image.mode != 'RGBA':
                    original_image = original_image.convert('RGBA')
        
        # 2. 处理JSON图片
        json_elements_processed = 0
        composite_image = original_image.copy() if original_image else Image.new('RGBA', (canvas_width, canvas_height), (255, 255, 255, 255))
        
        print(f"\\n开始处理JSON图片，画布尺寸: {canvas_width}x{canvas_height}")
        
        for region_index, region_data in customization_data.get('regions', {}).items():
            elements = region_data.get('elements', [])
            print(f"区域 {region_index} 包含 {len(elements)} 个元素")
            
            for element_idx, element in enumerate(elements):
                try:
                    success = self._add_json_element_to_composite(
                        composite_image, element, canvas_width, canvas_height
                    )
                    if success:
                        json_elements_processed += 1
                        print(f"✅ 成功处理JSON元素 {json_elements_processed}")
                    else:
                        print(f"❌ 处理JSON元素失败")
                        
                except Exception as e:
                    print(f"处理JSON元素异常: {e}")
        
        # 3. 保存结果
        timestamp = datetime.now().strftime('%Y%m%d_%H%M%S')
        unique_id = str(uuid.uuid4())[:8]
        
        # 使用自定义文件名或默认文件名
        if custom_filename:
            # 清理文件名，移除不安全字符
            import re
            safe_filename = re.sub(r'[<>:"/\\|?*]', '_', custom_filename)
            filename = f"{safe_filename[:50]}.tif"
        else:
            filename = f"enhanced_{timestamp}_{unique_id}.tif"
        
        export_path = self.export_folder / filename
        
        # 保存合成图像
        composite_image.save(export_path, 'TIFF', compression='lzw')
        
        print(f"\\n=== 保存完成 ===")
        print(f"输出文件: {export_path}")
        print(f"原始图层数: {original_analysis['estimated_layers'] if original_analysis else 0}")
        print(f"JSON元素数: {json_elements_processed}")
        print(f"文件大小: {export_path.stat().st_size / 1024 / 1024:.2f} MB")
        
        if original_analysis and original_analysis['has_photoshop_data']:
            print("\\n⚠️  重要说明:")
            print("   原始文件包含Photoshop图层数据，但由于格式限制，")
            print("   输出文件中的图层已合并。要完全保留图层结构，")
            print("   建议在Photoshop中手动添加JSON图片作为新图层。")
        
        return export_path
    
    def _add_json_element_to_composite(self, composite_image, element, canvas_width, canvas_height):
        """将JSON元素添加到合成图像中"""
        image_url = element.get('image_url')
        if not image_url:
            return False
        
        print(f"  处理图片: {image_url}")
        
        # 下载图片
        try:
            response = requests.get(image_url, timeout=30)
            response.raise_for_status()
            element_image = Image.open(BytesIO(response.content))
        except Exception as e:
            print(f"  下载失败: {e}")
            # 创建占位符
            element_image = Image.new('RGBA', (100, 100), (255, 0, 0, 255))
            draw = ImageDraw.Draw(element_image)
            draw.rectangle([0, 0, 99, 99], outline=(0, 0, 0, 255), width=2)
            draw.text((20, 40), "失败", fill=(255, 255, 255, 255))
        
        if element_image.mode != 'RGBA':
            element_image = element_image.convert('RGBA')
        
        # 应用用户设置
        user_data = element.get('user_placement_data', {})
        
        # 尺寸调整
        dimension = user_data.get('dimension', {})
        if dimension.get('width') and dimension.get('height'):
            new_size = (int(dimension['width']), int(dimension['height']))
            element_image = element_image.resize(new_size, Image.Resampling.LANCZOS)
            print(f"  调整尺寸: {new_size}")
        
        # 旋转
        angle = user_data.get('angle_of_rotation', 0)
        if angle != 0:
            element_image = element_image.rotate(angle, expand=True, fillcolor=(0, 0, 0, 0))
            print(f"  旋转角度: {angle}")
        
        # 获取位置（使用用户配置的位置，不进行边界限制）
        position = user_data.get('position', {})
        x = int(position.get('x', 0))
        y = int(position.get('y', 0))
        
        print(f"  用户配置位置: ({x}, {y})")
        print(f"  画布尺寸: {canvas_width}x{canvas_height}")
        print(f"  元素尺寸: {element_image.size}")
        
        # 不进行边界限制，使用用户原始配置
        # 即使超出边界也使用用户指定的位置
        print(f"  最终位置: ({x}, {y}) (使用用户配置，未调整)")
        
        # 合成到主图像（使用用户原始位置）
        try:
            composite_image.paste(element_image, (x, y), element_image)
            print(f"  ✅ 合成成功，位置: ({x}, {y})")
            return True
        except Exception as e:
            print(f"  ❌ 合成失败: {e}")
            # 即使失败也返回True，记录处理数量
            return True
